package app.framework.security.authentication;

import app.framework.constant.FrontConstants;
import app.framework.front.util.WebUtil;
import app.framework.security.csrf.CsrfTokenUtil;
import app.framework.security.util.LoginAttemptCountUtil;
import jasmine.framework.common.util.JsonUtil;
import jasmine.framework.web.entity.WebResult;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * Spring Security 认证成功后响应 JSON 格式的内容。
 * </p>
 *
 * @author mh.z
 */
public class AuthenticationSuccessJsonResultHandler implements AuthenticationSuccessHandler {
    private String usernameParameter;

    public AuthenticationSuccessJsonResultHandler(String usernameParameter) {
        this.usernameParameter = usernameParameter;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        // 设置响应体信息
        WebUtil.setResponseInfo(response, HttpServletResponse.SC_OK,
                FrontConstants.RESPONSE_CONTENT_TYPE_JSON);

        // 设置 CSRF 令牌
        CsrfTokenUtil.setCsrfToken(request, response);

        WebResult result = WebResult.success();
        String json = JsonUtil.toJson(result);
        // 写入数据到响应体
        WebUtil.writeAndFlush(response, json);

        String username = request.getParameter(usernameParameter);
        // 重置登录尝试次数
        LoginAttemptCountUtil.resetAttemptCount(username);
    }

}
